import 'package:app/common/app_theme.dart';
import 'package:app/common/colors.dart';
import 'package:app/components/base_scaffold_appbar.dart';
import 'package:app/pages/daily_calendar_report_module/my_calendar_detail_module/calendar_event_model.dart';
import 'package:app/pages/daily_calendar_report_module/my_calendar_module/my_calendar_model.dart';
import 'package:app/router/app_pages.dart';
import 'package:app/services/address.dart';
import 'package:app/services/dio_manager.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../../common/tool.dart';
import '../../../components/nodata_page.dart';
import '../../../utils/calender.dart';
import 'package:get/get.dart';

import 'my_calendar_room_model.dart';
class MYCalendarPage extends StatefulWidget {
  const MYCalendarPage({Key? key}) : super(key: key);

  @override
  State<MYCalendarPage> createState() => _MYCalendarPageState();
}

class _MYCalendarPageState extends State<MYCalendarPage> {




  CalendarFormat _calendarFormat = CalendarFormat.week;
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;


  List dataArr = [];


  @override
  void initState() {
    var timeFormat = DateFormat("yyyy-MM-dd");
    var timeStr = timeFormat.format(DateTime.now());

    _selectedDay = DateTime.now();
    // print(timeStr);
    // requestDataWithGetCalendarRoom(timeStr);
    requestData(timeStr);
    requestDataWithEventData('${DateTime.now().year}-${DateTime.now().month}-01',
        '${DateTime.now().year}-${DateTime.now().month}-30');
  }

  // requestDataWithGetCalendarRoom(var start_time)async{
  //
  //   var params = {
  //     'start_time':'${start_time}',
  //     'end_time':'${start_time}',
  //     'allday':'1',
  //   };
  //   var json = await DioManager().kkRequest(Address.calendarRoom,params: params,method: 'get');
  //
  //   MyCalendarRoomModel model = MyCalendarRoomModel.fromJson(json);
  //
  //   dataArr.clear();
  //   dataArr.addAll(model.data!);
  //
  //   setState(() {
  //
  //   });
  // }

  /// 日历
  requestData(var start_time)async{

    var params = {
      'start_time':'${start_time}',
      'end_time':'${start_time}',
      'limit':'1000',
      'page':'1',
    };
    var json = await DioManager().kkRequest(Address.calendarPage,params: params,method: 'get');

    MyCalendarModel model = MyCalendarModel.fromJson(json);
    dataArr.clear();

    if(model.data!=null){
      dataArr.addAll(model.data!);
    }

    setState(() {

    });
  }

  CalendarEventModel? calendarEventModel;
  /// 搜索日期范围内有事件的日期
  requestDataWithEventData(var startTime, var endTiem)async{

    var params = {
      'start_time':'${startTime}',
      'end_time':'${endTiem}',
    };
    var json = await DioManager().kkRequest(Address.calendarEventDate,params: params,method: 'get');

    CalendarEventModel _model = CalendarEventModel.fromJson(json);

    calendarEventModel = _model;

    setState(() {

    });
  }

  List<Event> _getEventsForDay(DateTime day) {
    // Implementation example
    // return kEvents[day] ?? [];
    return kEvents[day]??[];
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.bgColor,
      appBar: BaseAppBar(child: Text('日程'),preferredSize: Size(Get.width, AppTool.appBarHEIGHT),
      action: [
        TextButton(onPressed: ()async{
          var data = await Get.toNamed(AppRoutes.publishedCalendar,arguments: -1);
          if(data == 'refresh'){
            var timeFormat = DateFormat("yyyy-MM-dd");
            var timeStr = timeFormat.format(DateTime.now());
            requestData(timeStr);
            requestDataWithEventData('${DateTime.now().year}-${DateTime.now().month}-01',
                '${DateTime.now().year}-${DateTime.now().month}-30');
          }
        }, child: Text('新建',style: TextStyle(color: Colors.white),))
      ],
      ),
      body: Container(
        color: AppColor.bgColor,
        child: EasyRefresh.custom(
            onRefresh: ()async{
              var timeFormat = DateFormat("yyyy-MM-dd");
              var timeStr = timeFormat.format(_selectedDay!);
              requestData(timeStr);
              requestDataWithEventData('${DateTime.now().year}-${DateTime.now().month}-01',
                  '${DateTime.now().year}-${DateTime.now().month}-30');
              },
            // emptyWidget:dataArr.length==0?NoDataPage():null,
            // header: MaterialHeader(),
            slivers:[
              SliverToBoxAdapter(
            child: TableCalendar(
              locale: 'zh_CN',
              firstDay: kFirstDay,
              lastDay: kLastDay,
              focusedDay: _focusedDay,
              calendarFormat: _calendarFormat,
              eventLoader: (eventLoader){

                var timeFormat = DateFormat("yyyy-MM-dd");
                var eventTimeStr = timeFormat.format(eventLoader);

                // var todayStr = timeFormat.format(kToday);
                // print('eventLoader ======= ${eventTimeStr} today=====${todayStr}');

                // if(eventTimeStr == todayStr){
                //   List<Event> s = [
                //     Event('111',),
                //     Event('111',),
                //   ];
                //   return s;
                // }
                if(calendarEventModel?.data==null){
                  return [];
                }

                for(int i = 0;i<calendarEventModel!.data!.length;i++){
                  if(eventTimeStr == calendarEventModel!.data![i].date){
                    List<Event> list = List.generate(calendarEventModel!.data![i].num!, (index)
                    => Event('111',));
                    return list;
                  }
                }
                return [];
              },
              calendarStyle: CalendarStyle(
                // Use `CalendarStyle` to customize the UI
                outsideDaysVisible: false,

              ),
              selectedDayPredicate: (day) {
                // Use `selectedDayPredicate` to determine which day is currently selected.
                // If this returns true, then `day` will be marked as selected.

                // Using `isSameDay` is recommended to disregard
                // the time-part of compared DateTime objects.

                return isSameDay(_selectedDay, day);
              },
              onDaySelected: (selectedDay, focusedDay) {
                if (!isSameDay(_selectedDay, selectedDay)) {
                  // Call `setState()` when updating the selected day
                  var timeFormat = DateFormat("yyyy-MM-dd");
                  var timeStr = timeFormat.format(selectedDay);
                  print(timeStr);

                  // requestDataWithGetCalendarRoom(timeStr);

                  requestData(timeStr);

                  setState(() {
                    _selectedDay = selectedDay;
                    _focusedDay = focusedDay;
                  });
                }
              },
              onFormatChanged: (format) {
                if (_calendarFormat != format) {
                  // Call `setState()` when updating calendar format
                  setState(() {
                    _calendarFormat = format;
                  });
                }
              },
              onPageChanged: (focusedDay) {
                // No need to call `setState()` here
                _focusedDay = focusedDay;

                print('_focusedDay ==== ${focusedDay}');

                requestDataWithEventData('${focusedDay.year}-${focusedDay.month}-01',
                    '${focusedDay.year}-${focusedDay.month}-30');

                // requestDataWithEventData();
              },
            ),
          ),

              dataArr.length==0?SliverToBoxAdapter(
                child: NoDataPage(),
              ): SliverList(
            delegate: _mySliverChildBuilderDelegate(),
          ),
        ]),
      ),
    );
  }
  _mySliverChildBuilderDelegate() {
    return SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            MyCalendarItemModel model = dataArr[index];
        return SwipeActionCell(
          trailingActions: <SwipeAction>[
            SwipeAction(
                title: "删除",
                onTap: (CompletionHandler handler) async {
                  var params = {
                    'calendar_id':model.id,
                  };
                  var json = await DioManager().kkRequest(Address.calendarUnlink,bodyParams: params);

                  // controller.requestDataWithUnlink(document_id: model.id).then((value)async {
                    if(json['errmsg']=='no'){
                      await handler(false);
                    }else{
                      await handler(true);
                    }
                  // });

                },
                color: Colors.red),
          ],
          key: ObjectKey(dataArr[index]),
          child:   GestureDetector(
          onTap: () async{
            // controller.pushToView(index);

            var data = await Get.toNamed(AppRoutes.calendarDetail,arguments: model.id);

            if(data == 'refresh'){

              var timeFormat = DateFormat("yyyy-MM-dd");
              var timeStr = timeFormat.format(_selectedDay!);

              requestData(timeStr);
              requestDataWithEventData('${DateTime.now().year}-${DateTime.now().month}-01',
                  '${DateTime.now().year}-${DateTime.now().month}-30');
            }
            // Get.to(page);
          },
          child: Container(
            margin: EdgeInsets.only(left: 5,right: 5,top: 5),
            color: Colors.white,
            padding: EdgeInsets.only(left: 10,right: 25,top: 10,bottom: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: Get.width - 50,
                      child: Text('${model.name}',style: appThemeData.textTheme.bodyText1!.copyWith(
                        fontSize: 16,
                      ),),
                    ),
                    // Text('状态：${model.state}'),
                  ],
                ),
                SizedBox(height: 5,),
                Text('组织者：${model.userName}',style: appThemeData.textTheme.subtitle1,),
                SizedBox(height: 5,),
                Row(
                  children: [
                    Text('时间：${model.start}',style: appThemeData.textTheme.subtitle1,),
                    Text('~'),
                    Text('${model.stopDate}',style: appThemeData.textTheme.subtitle1,),
                  ],
                ),
              ],
            ),
          ),
        ),

        );

      },
      childCount: dataArr.length,
    );
  }

}
